package com.shopmall.common.jwt;

import com.alibaba.fastjson.JSON;
import com.shopmall.common.ResponseData;
import com.shopmall.system.service.impl.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtTokenAuthFilter extends OncePerRequestFilter {
    @Resource
    UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken = request.getHeader("Authorization");
        if (!ObjectUtils.isEmpty(jwtToken)) {
            jwtToken = jwtToken.replaceAll("Bearer ","");
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey("abcerwrw")
                        .parseClaimsJws(jwtToken)
                        .getBody();
                String username = claims.getSubject();
                UserDetails userDetails = userService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            } catch (Exception e) {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.print(JSON.toJSONString(new ResponseData().failed("token已过期，请重新登录")));
                out.flush();
                out.close();
                return;
            }
        }
//        else{
//            response.setContentType("application/json;charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.print(JSON.toJSONString(new ResponseData().failed("401","请重新登录")));
//            out.flush();
//            out.close();
//            return;
//        }
        filterChain.doFilter(request, response);
    }
}
